import Food from './Food';
import Snake from './Snake';
import ScorePanel from './ScorePanel';
// 游戏控制类
class GameControl {
    scorePanel: ScorePanel;
    food: Food;
    snake: Snake;
    // 蛇的方向
    direction: string = '';
    asdasa: number = 1000

    // 游戏是否结束
    isLive: boolean = true

    constructor() {
        this.scorePanel = new ScorePanel();
        this.food = new Food();
        this.snake = new Snake();
    }


    // 游戏初始化方法,调用后游戏开始
    init() {
        document.addEventListener('keydown', this.keydownHander.bind(this))
        //
        this.run()
    }

    // 创建一个键盘按下的响应函数
    keydownHander(event: KeyboardEvent) {
        this.direction = event.key;
    }

    // 控制蛇移动的方法
    run() {
        let X: number = this.snake.X
        let Y: number = this.snake.Y
        switch (this.direction) {
            // 向上，top -10
            case 'ArrowUp':
            case "up":
                Y -= 10
                break;
            case 'ArrowDown':
            case "Down":
                Y += 10
                break;
            case 'ArrowLeft':
            case "Left":
                X -= 10
                break;
            case 'Right':
            case "ArrowRight":
                X += 10
                break;
            default:
                break;
        }
        // 将移动的后变化的值重新赋值
        try {
            this.snake.Y = Y
            this.snake.X = X
            this.eatFood(X,Y)
        } catch (e) {
            alert(e.message)
            this.isLive = false
        }
        // 开启一个定时器,调用该 run 函数本身，由于是在 run 函数结束前调用的，相当于循环定时器, 定时器的时间是由游戏等级调整的
        this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30)
    }

    // 吃到了食物,参数为蛇头的坐标
    eatFood(X: number, Y: number) {
        if (this.food.X === X && this.food.Y === Y){
            // 分数增加
            this.scorePanel.addScore()
            // 调整食物位置
            this.food.change()
            // 增加蛇身体
            this.snake.addBody()
        }
    }
}
export default GameControl